//
//  HWDropdownMenu.m
//  01-黑马微博
//
//  Created by lanou3g on 15/9/7.
//  Copyright (c) 2015年 heima. All rights reserved.
//

#import "HWDropdownMenu.h"
@interface HWDropdownMenu ()
@property (nonatomic, weak) UIImageView *contentView;
@end
@implementation HWDropdownMenu
- (UIImageView *)contentView{
    if (!_contentView) {
        UIImageView *contentView = [[UIImageView alloc] init];
        contentView.image = [UIImage imageNamed:@"popover_background"];
//        contentView.width = 217;
//        contentView.height = 300;
        contentView.userInteractionEnabled = YES;
        [self addSubview:contentView];
        self.contentView = contentView;
           }
    return _contentView;
}
- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        
    }
    return self;
}
+ (instancetype)menu
{
    return [[self alloc] init];
}
- (void)setChildView:(UIView *)childView{
    _childView = childView;
    /**
     *  调整内容位置
     */
    childView.x = 10;
    childView.y = 15;
//   吊证内容位置
//    childView.width = self.contentView.width - 2 * childView.x;
//    设置菜单的尺寸
    self.contentView.height = CGRectGetMaxY(childView.frame) + 10;
//    设置灰色的宽度
    self.contentView.width = CGRectGetMaxX(childView.frame) + 10;
    [self.contentView addSubview:childView];
}
- (void)showFrom:(UIView *)from;
{
//    1.获得最上层window
    UIWindow *window = [[UIApplication sharedApplication].windows lastObject];
//    2.添加自己到窗口上
    [window addSubview:self];
//    3.设置吃春
    self.frame = window.frame;
//    4.调整灰色图片frame
//    4.1坐标系转换
    CGRect newFrame = [from.superview convertRect:from.frame toView:window];
    CGFloat centerX = CGRectGetMidX(newFrame);
    self.contentView.centerX = centerX;
    self.contentView.y = CGRectGetMaxY(newFrame);
    if (self.delegate && [self.delegate respondsToSelector:@selector(dropdownMenuDidShow:)]) {
        [self.delegate dropdownMenuDidShow:self];
    }
}
/**
 *  设置控制器
 */ - (void)setDropVc:(UIViewController *)dropVc{
    _dropVc = dropVc;
    self.childView = dropVc.view;
}
- (void)dismiss{
    [self removeFromSuperview];
    if (self.delegate && [self.delegate respondsToSelector:@selector(dropdownMenuDidDismiss:)]) {
        [self.delegate dropdownMenuDidDismiss:self];
    }
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self dismiss];
}
@end
